<template>
  <div class="home">
    <div class="title">
      <img src="../assets/images/logo.png" width="100px">
      <img src="../assets/images/testname.png" width="40%">
      <img src="../assets/images/title.png" width="80%">
    </div>
    <div class="button_group">
      <router-link to="/about?tabindex=2">
        <img src="../assets/images/rank.png">
      </router-link>
      <router-link to="/about?tabindex=3">
        <img src="../assets/images/group.png">
      </router-link>
      <img src="../assets/images/myscore.png" @click="score">
    </div>
    <div class="enter">
      <img src="../assets/images/enter.png" width="40%" @click="wxlogin">
      <img src="../assets/images/company.png" width="40%">
    </div>
  </div>
</template>

<script>
  import HelloWorld from '@/components/HelloWorld.vue'
  import {
    post
  } from '../assets/utils/axiosRequest'
  export default {
    name: 'Home',
    components: {
      HelloWorld
    },
    data() {
      return {
        code: ""
      };
    },
    created() {},
    methods: {
      score() {
        if (localStorage.getItem("WZTLUNIONID")) {
          let data = new FormData();
          var userIdentify = localStorage.getItem("WZTLUNIONID")
          data.append('eventId', '3');
          data.append('userIdentify', userIdentify);
          post("/gt-contest/contest/getScore", data).then(res => {
            if (res.code == "000000") {
              if (res.result != null) {
                this.$router.push({
                  path: "/score",
                  query: {
                    score: res.result.score,
                    usertime: res.result.timeCost
                  }
                })
              } else {
                this.$message({
                  message: '暂未查询到成绩，请先进行考试',
                  type: 'warning'
                });

              }
            } else {
              this.$message({
                message: '抱歉，网络异常',
                type: 'warning'
              });
            }
          })
        } else {
          this.$message({
            message: '暂未查询到成绩，请先进行考试',
            type: 'warning'
          });
        }

      },
      getCode() { // 非静默授权，第一次有弹框
        var that = this
        this.code = this.getUrlCode("code") // 截取code
        console.log("code=" + this.code)
        if (this.code == null || this.code === '' || this.code == undefined) { // 如果没有code，则去请求
          var appid = this.$store.state.appid
          var url = "http://www.wxrb.com/gt-contest-h5/index.html"
          var UrlEncode = encodeURIComponent(url)
          window.location.href =
            `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${UrlEncode}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
        } else {
          //根据code获取用户信息
          let data = new FormData();
          data.append('code', this.code)
          post("/gt-contest/sso/getOpenId", data).then(res => {
            var code = res.code
            if (code == "000000") {
              console.log(res.result)
              var openid = res.result.openid
              that.$store.state.openId = openid
              localStorage.setItem("WZTLUNIONID", openid)
              localStorage.setItem("headimgurl", res.result.headimgurl)
              that.$store.state.headimgurl = res.result.headimgurl
              this.$router.push({
                path: "/info"
              })
            } else if (code == "-1") {
              this.$message({
                message: '请用户先关注【无锡市自然资源和规划局】公众号',
                type: 'warning'
              });
            } else {
              this.$message({
                message: '网络异常，请联系管理员',
                type: 'warning'
              });
            }

          })
        }
      },
      getUrlCode(parameName) { // 截取url中的code方法
        /// 获取地址栏指定参数的值
        // 获取url中跟在问号后面的部分
        var parames = window.location.search;
        if (parames.indexOf(parameName) > -1) {
          var parameValue = "";
          parameValue = parames.substring(
            parames.indexOf(parameName),
            parames.length
          );
          // 检测后面是否还有参数
          if (parameValue.indexOf("&") > -1) {
            // 去除后面多余的参数, 得到最终 parameName=parameValue 形式的值
            parameValue = parameValue.substring(
              0,
              parameValue.indexOf("&")
            );
            // 去掉参数名, 得到最终纯值字符串
            parameValue = parameValue.replace(parameName + "=", "");
            return parameValue;
          }
          return "";
        }
      },
      wxlogin() {
        post("/gt-contest/contest/canAnswer").then(res => {
          if (res.code == "000000") {
            if (res.result) {
              if (localStorage.getItem("WZTLUNIONID")) {
                this.toinfo()
              } else {
                this.getCode()
              }
            } else {
              this.$message({
                message: '竞赛答题考试尚未开始，考试时间为2021年8月30日10∶00—9月3日24∶00，敬请期待！',
                type: 'warning'
              });
            }
          } else {
            this.$message({
              message: '网络异常，请联系管理员',
              type: 'warning'
            });
          }
        })


      },
      //this.appid 公众号APPID  this.url  用户点击授权后，会跳转到后台帮我们重定向的页面（这里我是新建了一个空白页，专门接收code）
      toinfo() {
        let data = new FormData();
        var userIdentify = localStorage.getItem("WZTLUNIONID")
        data.append('eventId', '3');
        data.append('userIdentify', userIdentify);
        post("/gt-contest/contest/getScore", data).then(res => {
          if (res.code == "000000") {
            if (res.result != null) {
              this.$router.push({
                path: "/score",
                query: {
                  score: res.result.score,
                  usertime: res.result.timeCost
                }
              })
            } else {
              if (localStorage.getItem("ifregister")) {
                this.$router.push({
                  path: "/exam"
                })
              } else {
                this.$router.push({
                  path: "/info"
                })
              }
            }
          } else {
            this.$message({
              message: '网络异常，请联系管理员',
              type: 'warning'
            });
          }
        })
      }
    }
  }
</script>
<style scoped lang="less">
  .home {
    width: 100%;
    height: 100%;
    background: url('../assets/images/loadingbg.png');
    background-size: 100% 100%;

    .title,
    .button_group,
    .enter {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }

    .title {
      top: 10%;
      position: relative;

      img {
        margin: 10px 0;
      }
    }

    .button_group {
      position: fixed;
      right: 10px;
      top: 40px;


      img {
        width: 80px;
      }
    }

    .enter {
      position: fixed;
      bottom: 100px;
    }
  }
</style>